#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import json
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest
from conf import config
from utils import init_log, logger, expose
from traceback import format_exc
from xyf_customtag import XyfCustomtag


class Server(object):

    def __init__(self):
        self._pid = os.getpid()
        if not os.path.exists(config.log_path):
            os.makedirs(config.log_path)
        log_name = '{}.{}'.format(config.log_name, self._pid)
        init_log(config.log_path, log_name)
        logger.debug('server is running...')

    def _rsp_encode(self, rsp):
        return json.dumps(rsp, separators=(',', ':'))

    def _req_decode(self, req):
        return json.loads(req)

    def _errcode(self, code=0, msg='ok'):
        return dict(errcode=code, errmsg=msg)

    def _response(self, response):
        encode_response = self._rsp_encode(response)
        return Response(encode_response, mimetype='application/json')

    @expose('/xyf_customtag', methods=['POST'])
    def api_xyf_customtag(self, request):
        try:
            data = request.get_data()
            logger.debug('api_xyf_customtag request:%s', data)
            org_data = self._req_decode(data)
            if org_data is None:
                raise BadRequest()
            response = self._errcode(0)
            response['data'] = XyfCustomtag(org_data).get_xyf_customtag()
        except KeyError as e:
            logger.error("xyf_customtag parameter error %s", format_exc())
            response = self._errcode(-201, e.message)
        except Exception as e:
            logger.error('xyf_customtag except %s', format_exc())
            response = self._errcode(-200, e.message)

        return self._response(response)


g_server = Server()


if __name__ == "__main__":
    pass
